/**
 * 
 */

package com.kugou.game.sdk.ui.fragment;

import com.kugou.framework.base.LogUtil;
import com.kugou.framework.utils.NetWorkUtil;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseSDKWorkerFragment;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.AccountSecurityInfo;
import com.kugou.game.sdk.interfaces.onAccountSecurityInfoListener;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.dialog.SelectOptionDialog;
import com.kugou.game.sdk.ui.dialog.SelectOptionDialog.OnSelectOptionListener;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.Rx;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * 描述:设置密保问题
 *
 * @author jerryliu
 * @since 2015年8月19日 下午3:04:30
 */
public class SetSecurityQuestionFragment extends BaseSDKWorkerFragment implements OnClickListener {
    private static final int MSG_BACK_SET_SECURITY_QUESTION = 11;

    private static final int MSG_UI_SET_SECURITY_QUESTION_SUCCESS = 12;

    private static final int MSG_UI_SET_SECURITY_QUESTION_FAILE = 13;

    private Activity context;

    private TextView tvSecurityQuestion, tvAccount;

    private ImageView ivSelectArrow;

    private EditText etSecurityAnswer, etLoginPsd;

    private Button btnConfirm;

    private LoadingView loadingView;

    private View layoutContent;

    private User user;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        user = UserManager.getInstance().getCurrentUserInternal();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(Rx.layout.kg_fragment_set_security_question, null);
        initView(view);
        setListener();
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    private void initView(View view) {
        loadingView = (LoadingView) view.findViewById(Rx.id.kg_loadingView);
        loadingView.setText("正在操作，请稍候…");
        layoutContent = view.findViewById(Rx.id.kg_layout_bind_phone);
        tvAccount = (TextView) view.findViewById(Rx.id.kg_tv_username);
        tvAccount.setText(user.getAccountName());
        etLoginPsd = (EditText) view.findViewById(Rx.id.kg_et_psd);
        tvSecurityQuestion = (TextView) view.findViewById(Rx.id.kg_et_phone_number);
        etSecurityAnswer = (EditText) view.findViewById(Rx.id.kg_et_auth_code);
        ivSelectArrow = (ImageView) view.findViewById(Rx.id.kg_tv_get_auth_code);
        ivSelectArrow.setOnClickListener(this);
        btnConfirm = (Button) view.findViewById(Rx.id.kg_btn_confirm);
    }

    private void setListener() {
        ivSelectArrow.setOnClickListener(this);
        tvSecurityQuestion.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (v == ivSelectArrow || v == tvSecurityQuestion) {
            showSelectQuestionDialog();
        } else if (v == btnConfirm) {
            hideSoftInput(context);
            if (!NetWorkUtil.isNetworkAvailable(context)) {
                showToast("请检查您的网络连接");
                return;
            }

            String loginPsd = etLoginPsd.getText().toString().trim();
            if (TextUtils.isEmpty(loginPsd)) {
                showToast("请输入登录密码");
                return;
            }

            // if (!loginPsd.equals(user.getPassword())) {
            // showToast("您输入的密码不正确");
            // return;
            // }

            String question = tvSecurityQuestion.getText().toString().trim();
            if (TextUtils.isEmpty(question)) {
                showToast("请选择密保问题");
                return;
            }

            String answer = etSecurityAnswer.getText().toString().trim();
            if (TextUtils.isEmpty(answer)) {
                showToast("请输入密保答案");
                return;
            }

            loadingView.setVisibility(View.VISIBLE);
            layoutContent.setVisibility(View.GONE);
            sendEmptyBackgroundMessage(MSG_BACK_SET_SECURITY_QUESTION);
        }
    }

    private int questionIndex = -1;

    SelectOptionDialog dialog = null;

    private void showSelectQuestionDialog() {
        if (dialog == null) {
            dialog = new SelectOptionDialog(getActivity());
            dialog.setDialogTitle("请选择密码保护问题");
            ArrayList<String> options = new ArrayList<String>();
            options.add("你在哪所中学读高中？");
            options.add("你的宠物叫什么名字？");
            options.add("你最喜欢的音乐是？");
            options.add("你最喜欢的球队是？");
            options.add("你最喜欢的书是？");
            options.add("你最好的朋友是？");
            options.add("你的出生年月是？");
            options.add("你爱人的名字是？");
            options.add("你父亲的名字是？");
            options.add("你母亲的名字是？");
            dialog.addDatas(options);
            dialog.setDialogDefaultSize();
            dialog.setOnSelectOptionListener(new OnSelectOptionListener() {
                public void afterSelectUser(String option, int index) {
                    LogUtil.d("dax", option + " -- " + index);
                    questionIndex = index;
                    tvSecurityQuestion.setText(option);
                }
            });
        }
        dialog.setCurrentOptionIndex(questionIndex);
        dialog.show();
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        final Message message = new Message();
        String username = user.getAccountName();
        String answer = etSecurityAnswer.getText().toString().trim();
        String password = etLoginPsd.getText().toString().trim();
        switch (msg.what) {
            case MSG_BACK_SET_SECURITY_QUESTION:
                UserManager.getInstance().setSecurityQuestion(username, questionIndex, answer,
                        password, new onAccountSecurityInfoListener() {
                            @Override
                            public void onSuccess(AccountSecurityInfo info) {
                                message.what = MSG_UI_SET_SECURITY_QUESTION_SUCCESS;
                            }

                            @Override
                            public void onFaile(String errorMsg) {
                                message.what = MSG_UI_SET_SECURITY_QUESTION_FAILE;
                                message.obj = errorMsg;
                            }

                        });
                break;
        }

        sendUiMessage(message);
    }

    @Override
    public void handleUiMessage(Message msg) {
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }

        loadingView.setVisibility(View.GONE);
        layoutContent.setVisibility(View.VISIBLE);
        switch (msg.what) {
            case MSG_UI_SET_SECURITY_QUESTION_SUCCESS:
                showSuccessDialog();
                context.sendBroadcast(new Intent(SDKActions.ACTION_SET_SECURITY_QUESTION_SUCCESS));
                break;
            case MSG_UI_SET_SECURITY_QUESTION_FAILE:
                if (msg.obj != null) {
                    showToast(msg.obj.toString());
                }
                break;
        }
    }

    private void showSuccessDialog() {
        final BaseConfirmDialog dialog = new BaseConfirmDialog(context);
        dialog.setMessage("密保问题设置成功");
        dialog.setSuccessLogoVisibility(View.VISIBLE);
        dialog.setDialogTitle("提示");
        dialog.setCancelBtnVisibility(View.GONE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOKBtnText("知道了");
        dialog.setOkBtnBackground(Rx.drawable.kg_selector_bottom_single_filleted_corner_retangle);
        dialog.setCancelable(false);
        dialog.setOKClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();

                if (getActivity() != null && !getActivity().isFinishing()) {
                    getActivity().finish();
                }
            }

        });
        dialog.show();
    }
}
